package com.adbj.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABAtest {
    private static AtomicReference<String> atomicReference=new AtomicReference<>("A");
    private static AtomicStampedReference<String> stampedReference=new AtomicStampedReference<>("A",1);
    public static void main(String[] args) {
        new Thread(()->{
            int stamp=stampedReference.getStamp();
            System.out.println("t1获取版本号："+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            atomicReference.compareAndSet("A","B");
            atomicReference.compareAndSet("B","A");
            stampedReference.compareAndSet("A","B",stamp,stamp+1);
            stampedReference.compareAndSet("B","A",stamp+1,stamp+2);
            System.out.println("t1线程ABA之后的版本号："+stampedReference.getStamp());
        },"t1").start();

        new Thread(()->{
            int stamp=stampedReference.getStamp();
            System.out.println("t2获取版本号："+stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.print("普通原子类无法解决ABA问题： ");
            System.out.println(atomicReference.compareAndSet("A","C")+"\t"+atomicReference.get());
            System.out.print("版本号的原子类解决ABA问题： ");
            System.out.println(stampedReference.compareAndSet("A","C",stamp,stamp+1)+"\t"+stampedReference.getReference());
        },"t2").start();
    }
}
